using UnityEngine;
using System.Collections;
using Mono.Data.Sqlite;
using System;

public class InitScene : MonoBehaviour
{
	
	int sceneId;
	int count = 100;
	string databasePath;
	SqliteConnectionStringBuilder connstr;

    ScenePlayerLogic scenePlayerLogic;

	//GameObject panelNPC = GameObject.Find("Panel(NPC)");
	
	void Awake ()
	{
		//初始化摄像机//
		Camera main = Camera.mainCamera;
		GameObject unRemovedCamera = new GameObject();
		
		if(main != null){
			unRemovedCamera = main.gameObject;
			
			Transform mainRole = unRemovedCamera.transform.Find("mainRole");
			mainRole.localPosition = new Vector3 (-300, -210, 0);
		}else{	
			unRemovedCamera = (GameObject)Instantiate(Resources.Load(ResPath.UIPATH + "Camera(Unremoved)"));
		}

        scenePlayerLogic = Camera.mainCamera.GetComponent<ScenePlayerLogic>();
        scenePlayerLogic.addPlayer(PlayerData.Instance().MainRoleInstance);
		
		unRemovedCamera.transform.localPosition = Vector3.zero;
		
		Transform parentTrans = GameObject.Find ("Panel(NPC)").transform;
		
		sceneId = PlayerData.Instance ().SceneId;
		
		string[] sceneInfos = SqliteReader.getInstance ().getIniVal ("SceneInfo", "SceneID", sceneId.ToString (), false);
		
		PlayerData.Instance ().NextScene = int.Parse (sceneInfos [5]);
		
		//场景类型//
		int sceneType = int.Parse(sceneInfos[2]);
		
		if(sceneType == (int)GameDefine.SceneType.Fuben){
			gameObject.AddComponent<EncounterToFight>();
		}
		
		#region
		//s服务器表s.
		string serverScene = sceneInfos [7];	
		
		SqliteDataReader reader = SqliteReader.getInstance ().SelectAll (serverScene);
		
		while (reader.Read()) {
			int needInit = reader.GetInt32 (reader.GetOrdinal ("NeedInit"));//是否默认初始化//
			
			if (needInit == 0)
				continue;
			
			//s实例化s
			string prefabName = reader.GetString (reader.GetOrdinal ("PrefabName"));
			GameObject go = (GameObject)Instantiate (Resources.Load (ResPath.GENERALFILE + prefabName));
			Transform trans = go.transform;
			trans.parent = parentTrans;
            go.tag = prefabName;
			
			string id = reader.GetInt32 (reader.GetOrdinal ("ID")).ToString ();
			
			string[] npcInfo = SqliteReader.getInstance ().getIniVal ("Npc", "NpcID", id, false, new string[]{"NpcName","Model"});
			
			
			string objectName = reader.GetString (reader.GetOrdinal ("Name"));
			go.name = objectName;
			
			//s被实例化物体的大小s
			Vector3 scale = Vector3.one;
			int scaleX = reader.GetInt32 (reader.GetOrdinal ("ScaleX"));
			if (scaleX != 0) {
				scale.x = (float)scaleX;
				scale.y = (float)reader.GetInt32 (reader.GetOrdinal ("ScaleY"));
			}
			trans.localScale = scale;
			
			//s被实例化物体的位置s
			Vector3 position = Vector3.zero;
			position.x = (float)reader.GetInt32 (reader.GetOrdinal ("PosX"));
			position.y = (float)reader.GetInt32 (reader.GetOrdinal ("PosY"));
			trans.localPosition = position;
			
			//s被实例化物体的collider的信息s
			BoxCollider collider = go.GetComponent<BoxCollider> ();
			if (collider) {
				Vector3 center = collider.center;
				center.x = (float)reader.GetInt32 (reader.GetOrdinal ("ColliderPosX"));
				center.y = (float)reader.GetInt32 (reader.GetOrdinal ("ColliderPosY"));
				collider.center = center;
				
				Vector3 colliderScale = collider.size;
				colliderScale.x = (float)reader.GetInt32 (reader.GetOrdinal ("ColliderScaleX"));
				colliderScale.y = (float)reader.GetInt32 (reader.GetOrdinal ("ColliderScaleY"));
				collider.size = colliderScale;
			}
			
			//s物体帧动画的信息s
			ClipAnimation clipAni = go.GetComponentInChildren<ClipAnimation> ();
			if (clipAni) {
				clipAni.FPS = reader.GetInt32 (reader.GetOrdinal ("FrameSpeed"));
				clipAni.filePath = npcInfo [1];
			}
			
			//ss名字内容ss
			UILabel nameLable = go.GetComponentInChildren<UILabel> ();
			if (nameLable) {
				Vector3 namePos = nameLable.transform.localPosition;
				namePos.x = (float)reader.GetInt32 (reader.GetOrdinal ("NamePosX"));
				namePos.y = (float)reader.GetInt32 (reader.GetOrdinal ("NamePosY"));
				nameLable.transform.localPosition = namePos;
				nameLable.text = BinaryReaderTool.getInstance ().getSwfLangStr (npcInfo [0]);
			}
			
			//ss阴影的信息ss
			Transform shadow = trans.FindChild ("Shadow");
			if (shadow) {
				Vector3 shadowPos = shadow.localPosition;
				shadowPos.x = (float)reader.GetInt32 (reader.GetOrdinal ("ShadowPosX"));
				shadowPos.y = (float)reader.GetInt32 (reader.GetOrdinal ("ShadowPosY"));
				shadow.localPosition = shadowPos;
				Vector3 shadowScale = Vector3.one;
				shadowScale.x = (float)reader.GetInt32 (reader.GetOrdinal ("ShadowScaleX"));
				shadowScale.y = (float)reader.GetInt32 (reader.GetOrdinal ("ShadowScaleY"));
				shadow.localScale = shadowScale;
			}
			
			//ss任务状态的信息ss
			Transform taskTip = trans.FindChild ("TaskTip");
			if (taskTip) {
				TweenPosition tweenPosition = taskTip.GetComponent<TweenPosition> ();
				Vector3 fromPos = taskTip.localPosition;
				fromPos.x = (float)reader.GetInt32 (reader.GetOrdinal ("TaskStatusPosX"));
				fromPos.y = (float)reader.GetInt32 (reader.GetOrdinal ("TaskStatusPosY"));
				tweenPosition.from = fromPos;
				Vector3 toPos = fromPos;
				toPos += new Vector3 (0, 10, 0);
				tweenPosition.to = toPos;
			} else {
				PlayerAction monsterAction = go.GetComponent<PlayerAction> ();
				
				if(monsterAction == null){
					monsterAction = go.AddComponent<PlayerAction>();
				}
				
				float speed = (float)reader.GetInt32 (reader.GetOrdinal ("Speed"));
				monsterAction.speed = speed / 10.0f;
				float reapeatTime = (float)reader.GetInt32 (reader.GetOrdinal ("ReapeatTime"));
				monsterAction.reapeatRate = reapeatTime;
				float walkRadius = (float)reader.GetInt32 (reader.GetOrdinal ("WalkRadius"));
				monsterAction.radiusOfWalking = walkRadius / 10.0f;
				
				SceneFightNpc fightNpc = go.GetComponent<SceneFightNpc> ();
				
				if(fightNpc != null)
					fightNpc.MonsterId = int.Parse(id);
			}

            scenePlayerLogic.addNpc(go);
			
			/*
            string[] ConfigInfo = SqliteReader.getInstance().getIniVal(serverScene, "Name", objectName, new string[] { "ID", "Type", "Index" });//scene通过服务器消息取得//
            int typeId = int.Parse(ConfigInfo[0]);
            int type = int.Parse(ConfigInfo[1]);
            int index = int.Parse(ConfigInfo[2]);

            Point objID = new Point();
            objID.SetObjectID(1, typeId, (UInt32)type, (UInt32)index);

            SceneObject sceneObj = new SceneObject(objID, 0, 0);
            ModelLocator.getInstance().scene.HandlePropertiesEx(sceneObj.ObjKey, sceneObj);

            string[] ConfigBase = SqliteReader.getInstance().getIniVal("TeplatesInfo", "OType", type.ToString(), new string[] { "Struct", "Config" });

            InitXML.getInstance().AnalyzeXml(ConfigBase[0], ConfigBase[1], ConfigInfo[2], typeId.ToString(), sceneObj);
            */
		}
		#endregion
		
		//s客户端表s.
		//string clientScene = sceneInfos [8];
		string clientScene = sceneInfos [8];
		reader = SqliteReader.getInstance ().SelectAll (clientScene);
		while (reader.Read()) {
			string prefabName = reader.GetString (reader.GetOrdinal ("CommonPrefabName"));
			GameObject go = (GameObject)Instantiate (Resources.Load (ResPath.GENERALFILE + prefabName));
			Transform trans = go.transform;
			string objectName = reader.GetString (reader.GetOrdinal ("CommonID"));
			go.name = objectName;
			trans.parent = parentTrans;
			
			string fileName = reader.GetString (reader.GetOrdinal ("CommonFile"));
			
			//s所需资源文件s
			if (fileName != "null") {
				//s背景的图片s
				Texture texture = (Texture)Resources.Load (ResPath.BACKGROUNDTEXTURES + fileName);
				Material material = go.renderer.material;
				material.mainTexture = texture;
			}
			
			//s大小s
			Vector3 scale = trans.localScale;
			scale.x = (float)reader.GetInt32 (reader.GetOrdinal ("CommonScaleX"));
			scale.y = (float)reader.GetInt32 (reader.GetOrdinal ("CommonScaleY"));
			scale.z = (float)reader.GetInt32 (reader.GetOrdinal ("CommonScaleZ"));
			trans.localScale = scale;
			
			//s位置s
			Vector3 position = trans.localPosition;
			position.x = (float)reader.GetInt32 (reader.GetOrdinal ("CommonPosX"));
			position.y = (float)reader.GetInt32 (reader.GetOrdinal ("CommonPosY"));
			position.z = (float)reader.GetInt32 (reader.GetOrdinal ("CommonPosZ"));
			trans.localPosition = position;

            if (prefabName == "Door")
            {
                go.tag = "Npc";
                scenePlayerLogic.addNpc(go);
            }
		}
        //发送场景初始化完成//
	}
	
	/*
	void OnGUI ()
	{
		if (GUI.Button (new Rect (100, 100, 100, 50), "Click me")) {
			DbAccess access = new DbAccess (connstr.ToString ());
			SqliteDataReader reader = access.ReadFullTable ("RandomFamilyName");
			int i = 0;
			while (reader.Read()) {
				Debug.Log (reader.GetValue (0) + "<------>" + reader.GetValue (1));
			}
		}
	}
	*/
}
